<template>
  <a-modal
    title="商品推送"
    :width="'90%'"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-row :gutter="18">
      <a-col :span="16">
        <a-tabs :active-key="activeId" tabPosition="top" @change="handleChangeActiveId">
            <a-tab-pane v-for="item in flowType" :key="item.type">
                <template slot="tab">
                    {{ item.name }}
                </template>
                <a-table
                  size="middle"
                  bordered
                  :rowKey="rowKey"
                  :columns="columns"
                  :dataSource="dataSource"
                  :pagination="ipagination"
                  :loading="loading"
                  :scroll="{ y: 240 }"
                  :customRow="customRowFn"
                  :rowSelection="{selectedRowKeys, onChange: onSelectChange, type: 'checkbox'}"
                  @change="handleTableChange">
                </a-table>
            </a-tab-pane>
        </a-tabs>

      </a-col>
      <a-col :span="8">
        <a-card :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">
          <a-tabs :active-key="rightTabKey" tabPosition="top" @change="(key) => { rightTabKey = key }">
            <a-tab-pane key="selectTable" tab="已选商品">
              <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable">
                  <span slot="num" slot-scope="text, record">
                    <a-input-number :disabled="record.numberDisable" id="inputNumber" v-model="record.num" :min="1" :max="1000" />
                  </span>
                  <span slot="usePrice" slot-scope="text, record">
                    {{record.usePrice}}
                  </span>
                  <span slot="action" slot-scope="text, record, index">
                    <a @click="handleDeleteSelected(record, index)">删除</a>
                  </span>
              </a-table>
              <a-form-model ref="form">
                <a-form-model-item label="结算价格" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 20px">
                  <a-radio-group v-model="usePrice" @change="changeUsePrice">
                    <a-radio value="productFormatPrice"> 原价 </a-radio>
                    <a-radio value="productFormatDiscountPrice"> 折扣价 </a-radio>
                    <a-radio value="productFormatVipPrice"> 会员价 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <a-form-model-item label="商品总价" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <span>{{productTotalPrice}}元</span>
                </a-form-model-item>
              </a-form-model>
            </a-tab-pane>
            <a-tab-pane key="pushHistory" tab="推送二维码">
              <div v-if="pushObj.qrcodeUrl">
                <h3 style="margin-left: 20px; color: red;">请将二维码或链接地址发送至患者完成扫码支付！！！</h3>
                <p style="margin-left: 20px">推送时间：{{pushObj.createTime}}</p>
                <p style="margin-left: 20px">链接地址：https://shop.dtx-tech.com/mall/qrcode.html?content=order_qrcode|{{pushObj.dataId}}</p>
                <img :src="pushObj.qrcodeUrl" alt="" srcset="">
              </div>
              <div v-else>
                暂无推送记录
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>

  </a-modal>
</template>

<script>
  import Vue from 'vue'
  import { mapGetters } from 'vuex'
  import { USER_INFO } from "@/store/mutation-types"
  import { getAction, postAction, deleteAction } from '@/api/manage'
  import { cloneObject, pushIfNotExist } from '@/utils/util'

  export default {
    name: 'ProductPushModal',
    data() {
      return {
        title: '操作',
        visible: false,
        confirmLoading: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        activeId: 0,
        rowKey: 'dataId',
        flowType: [
            {
                type: 0,
                name: "全部"
            },
            {
                type: 1,
                name: "监测设备"
            },
            {
                type: 3,
                name: "服务"
            },
            {
                type: 4,
                name: "营养餐包"
            }
        ],
        columns: [
          {
              title: '商品名称',
              dataIndex: 'productName',
              key: 'productName',
              scopedSlots: { customRender: 'productName' }
          },
          {
              title: '商品原价',
              dataIndex: 'productFormatPrice',
              key: 'productFormatPrice',
              scopedSlots: { customRender: 'productFormatPrice' }
          },
          {
              title: '商品折扣价',
              dataIndex: 'productFormatDiscountPrice',
              key: 'productFormatDiscountPrice',
              scopedSlots: { customRender: 'productFormatDiscountPrice' }
          },
          {
              title: '商品会员价',
              dataIndex: 'productFormatVipPrice',
              key: 'productFormatVipPrice',
              scopedSlots: { customRender: 'productFormatVipPrice' }
          },
        ],
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['5', '10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
        loading: true,
        innerValue: [],
        // // 已选择列表
        selectedTable: {
          pagination: false,
          scroll: { y: 240 },
          columns: [
            {
                title: '商品名称',
                dataIndex: 'productName',
                key: 'productName',
                scopedSlots: { customRender: 'productName' }
            },
            {
                title: '数量',
                dataIndex: 'num',
                key: 'num',
                scopedSlots: { customRender: 'num' }
            },
            {
                title: '价格',
                dataIndex: 'usePrice',
                key: 'usePrice',
                scopedSlots: { customRender: 'usePrice' }
            },
            { title: '操作', dataIndex: 'action', align: 'center', width: 60, scopedSlots: { customRender: 'action' }, }
          ],
          dataSource: [],
        },
        usePrice: 'productFormatPrice',
        pushObj: {
          qrcodeUrl: ''
        },
        rightTabKey: 'pushHistory'
      }
    },
    created() {
    },
    computed: {
      productTotalPrice() {
        let price = this.selectedTable.dataSource.reduce((prev, item) => {
          prev += item.num * item[this.usePrice]
          return prev; 
        }, 0)
        return price.toFixed(2)
      }
    },
    watch: {
      activeId() {
          if (this.activeId >= 0) {
              this.dataSource = []
              console.log('activeId', this.activeId)
              this.loadData()
          }
      },
      selectedRowKeys: {
        immediate: true,
        deep: true,
        handler(val) {
          this.selectedTable.dataSource = val.map(key => {
            for (let data of this.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data.dataId)
                this.$set(data, 'num', 1)
                this.$set(data, 'usePrice', data[this.usePrice] ? data[this.usePrice] : 0)
                this.$set(data, 'numberDisable', data.productCategory == 3)
                return data
              }
            }
            for (let data of this.selectedTable.dataSource) {
              if (data[this.rowKey] === key) {
                pushIfNotExist(this.innerValue, data.dataId)
                this.$set(data, 'num', 1)
                this.$set(data, 'usePrice', data[this.usePrice] ? data[this.usePrice] : 0)
                this.$set(data, 'numberDisable', data.productCategory == 3)
                return data
              }
            }
            console.warn('未找到选择的行信息，key：' + key)
            return {}
          })
        },
      }
    },
    methods: {
      ...mapGetters(['doctorId']),
      show(patientId) {
        this.edit({
          orgCode: Vue.ls.get(USER_INFO).orgCode,
          patientId: patientId
        })
      },
      edit(record) {
        this.visible = true
        this.model = Object.assign({doctorId: this.doctorId()}, record)
        console.log(this.model)
        this.loadData();
        this.getLastPush();
      },
      customRowFn(record) {
        return {
          on: {
            click: () => {
              this.rightTabKey = 'selectTable'
              let key = record[this.rowKey]
              let index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys.push(key)
                this.$set(record, 'num', 1)
                this.$set(record, 'usePrice', record[this.usePrice] ? record[this.usePrice] : 0)
                this.$set(record, 'numberDisable', record.productCategory == 3)
                this.selectedTable.dataSource.push(record)
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      },
      /** 删除已选择的 */
      handleDeleteSelected(record, index) {
        this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
        //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
        this.selectedTable.dataSource.splice(this.selectedTable.dataSource.indexOf(record), 1)
        // this.innerValue.splice(this.innerValue.indexOf(record[this.valueKey]), 1)
        console.log("this.selectedRowKeys:",this.selectedRowKeys)
        console.log("this.selectedTable.dataSource:",this.selectedTable.dataSource)
        //update--begin--autor:wangshuai-----date:20200722------for：JSelectBizComponent组件切换页数值问题------
      },
      handleChangeActiveId(key) {
          this.activeId = key
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      handleTableChange(pagination, filters, sorter) {
        this.ipagination = pagination;
        this.loadData();
      },
      changeUsePrice() {
        this.selectedTable.dataSource.forEach((item, index) => {
          console.log("item[this.usePrice]", item[this.usePrice])
          this.$set(item, 'usePrice', item[this.usePrice] ? item[this.usePrice] : 0)
        })
      },
      loadData() {
        this.loading = true
        postAction('/shop/product/page', {
          productCategory: this.activeId,
          orgCode: Vue.ls.get(USER_INFO).orgCode
        }).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records||res.result;
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        }).finally(_ => {
          this.loading = false;
        })
      },
      getLastPush() {
        getAction('/shop/product/push/last', {
          patientId: this.model.patientId
        }).then((res) => {
          if (res.success) {
            if (res.result != null) {
              this.pushObj = res.result
              this.rightTabKey = 'pushHistory'
            } else {
              this.rightTabKey = 'selectTable'
            }
            console.log(this.pushObj)
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },
      handleSubmit() {
        const that = this
        // 触发表单验证
        if (that.selectedTable.dataSource.length > 0) {
          that.confirmLoading = true
          let products = []
          
          this.selectedTable.dataSource.forEach((item, index) => {
            products.push({
              id: item.dataId,
              num: item.num
            })
          })

          postAction('shop/product/push', {
            patientId: this.model.patientId,
            products,
            usePrice: this.usePrice,
            doctorId: this.doctorId()
          }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              that.$emit('ok');
              this.getLastPush()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.confirmLoading = false;
            // this.handleCancel();
          })
        } else {
          this.$message.error('请选择需要推送的商品')
        }
      },
      // 关闭
      handleCancel() {
        this.close()
      },
      close() {
        this.visible = false
        this.pushObj = {}
        this.selectedRowKeys = []
        this.selectedRow = []
        this.selectedTable.dataSource = []
      }
    }
  }
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>